package org.colour.amber.rest;

import static org.colour.amber.rest.UserRestController.PATH_USER;

import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.net.URI;
import java.time.LocalTime;
import java.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author jasonfu
 * @date 2021/8/19 16:28
 */
@Slf4j
@Tag(name = "HTTP Demo", description = "各种 HTTP 服务的示例")
@RestController
@RequestMapping(HttpRestController.PATH_HTTP)
public class HttpRestController {

    public static final String PATH_HTTP = "/api/v1/http";

    @GetMapping("/redirect")
    public ResponseEntity<?> redirect(UriComponentsBuilder uriBuilder) {
        URI uri = uriBuilder.path(PATH_USER + "/jasonfu").build().toUri();
        log.info("uri={}", uri);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(uri);
        return new ResponseEntity<>(headers, HttpStatus.FOUND);
    }

    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sse() {
        SseEmitter emitter = new SseEmitter();
        try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
            executor.execute(() -> {
                for (int i = 0; i < 5; i++) {
                    SseEventBuilder builder = SseEmitter.event()
                            .id(String.valueOf(i))
                            .data("SSE MVC - " + LocalTime.now())
                            .name("sse event - mvc");
                    try {
                        emitter.send(builder);
                        TimeUnit.SECONDS.sleep(1);
                    } catch (IOException | InterruptedException e) {
                        emitter.completeWithError(e);
                    }
                }
                emitter.complete();
            });
        }
        return emitter;
    }
}
